﻿using B.S.GridManage.Api.Write.DTOs;
using B.S.GridManage.ErrorCode;
using Consul;
using System.Net.Http.Json;

namespace B.S.GridManage.Api.Write.AearService
{

    /// <summary>
    /// 服务间内部的调用
    /// </summary>
    public class AreaServiceDiscovery
    {
        private readonly HttpClient httpClient;//用来发送请求的,类似axios ajax  apifox  swagger
        private readonly IConsulClient consulClient;//consul的客户端,可以用来查询某个服务的实例

        //第一步,构造函数里入住httpclient 和 httpFactory
        public AreaServiceDiscovery(IHttpClientFactory factory, IConsulClient consulClient)
        {
            this.httpClient = factory.CreateClient();
            this.consulClient = consulClient;
        }

        /// <summary>
        /// 根据服务名字查找服务,随机返回一个实例的地址
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>

        public async Task<string> GetUrlAsync(string serviceName)
        {
            var service = await consulClient.Health.Service(serviceName);//通过服务名从consul服务列表里查找服务
            var length = service.Response.Length; //数一数,找到的服务里有多少个实例,一个实例相当于一台服务器,它有自己的 IP+Port
            var index = new Random().Next(0, length - 1);
            var instance = service.Response[index];//通过下标随机取一个实例

            return $"http://{instance.Service.Address}:{instance.Service.Port}"; //返回实例的url  类似 http://localhost:1234
        }


        public async Task<ApiResult<List<AreaTreeDto>>> GetAreaTreeAsync(string url)
        {          
            var res = await httpClient.GetAsync(url);
            res.EnsureSuccessStatusCode();//设置200成功状态

            return await res.Content.ReadFromJsonAsync<ApiResult<List<AreaTreeDto>>>();
        }
    }
}
